package com.qst.itoffer.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@WebFilter(urlPatterns = "/*")
public class AuthorityFilter implements Filter {


    private static final String[] IGNORE_URIS = {
            "/login",
            "/validateCode",
            "/static/",
            "/css/",
            "/js/",
            "/images/",

    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession(false);

        String uri = request.getRequestURI();

        // 检查是否是不需要过滤的URI
        if (isIgnoreUri(uri)) {
            chain.doFilter(request, response);
            return;
        }

        // 检查用户是否已登录
        if (session == null || session.getAttribute("user") == null) {
            // 未登录，重定向到登录页面

            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        // 已登录，继续执行
        log.info("用户已登录：" + session.getAttribute("user"));
        chain.doFilter(request, response);
    }


    private boolean isIgnoreUri(String uri) {
        for (String ignoreUri : IGNORE_URIS) {
            if (uri.startsWith(ignoreUri) || uri.equals(ignoreUri) ) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        // 销毁操作
    }
}